package com.xncoding.pos;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.xncoding.pos.entity.User;
import com.xncoding.pos.repository.UserRepository;

@SpringBootApplication
@RestController
@RequestMapping("user")
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
    
    @Autowired
    private UserRepository userRepository;
    
    @RequestMapping("{id}")
    public User getUser(@PathVariable("id")Long id) {
    	return userRepository.getOne(id);
    }
    
    @RequestMapping("name/{name}")
    public Page<User> getUserByName(@PathVariable("name")String name,Integer currentPage) {
    	User user = new User();
    	user.setName(name);
    	if(currentPage == null) {
    		currentPage =0;
    	}
    	
    	ExampleMatcher matcher = ExampleMatcher.matching().withMatcher("name", ExampleMatcher.GenericPropertyMatchers.contains());
		Page<User> page = userRepository.findAll(Example.of(user, matcher),PageRequest.of(currentPage, 10, Direction.DESC, "id"));
    	return page;
    }
    
    @RequestMapping("list")
    public List<User> getUserList() {
    	return userRepository.findAll();
    }
    
    
    @RequestMapping("remove/{id}")
    public boolean remove(@PathVariable("id") Long id) {
    	userRepository.deleteById(id);
    	return true;
    }

}
